import { useEffect, useState } from 'react';
import { Layout, message } from 'antd';
import HistoryChat from '@/pages/app-qa/components/history-chat';
import Homepage from '@/pages/app-qa/components/homepage2';
import Chat from '@/pages/app-qa/components/chat';
import '@/pages/app-qa/styles/app-qa.css';

import { useOrchestrationStore } from '@/store/orchestrationStore';
import orchestrationService from '@/api/services/orchestrationService';
import { useUserInfo, useUserState } from '@/store/userStore';
import useWindowWidth from '@/hooks/event/use-window-width';
import Dashboard from '@/pages/report';
import { StartChatFnProps } from '@/pages/chat/tools/constants';
import { StreamResponseType } from '@/pages/chat/tools/fetch';
import { AppWorkbenchType } from '@/common/app/constants';
import { MenuContentType } from '@/common';
import { useParams } from '@/router/hooks';

interface AppQAProps {
  onStartChat?: (e: StartChatFnProps) => Promise<
    StreamResponseType & {
      isNewChat?: boolean;
    }
  >;
  changeContentType: (contentType: MenuContentType) => void;
  onUpdateHistory?: () => void;
  deleteCollectChat?: () => void;
  setContentType?: (contentType: MenuContentType) => void;
  workflowDebug?: boolean;
  contentType?: string;
  fusionChatId?: string;
  isDeleteChatHistory?: boolean;
  isAuthority?: boolean;
  isHomePage?: boolean | null;
}

const AppQA = ({
  onStartChat,
  onUpdateHistory,
  changeContentType,
  deleteCollectChat,
  setContentType,
  workflowDebug = false,
  contentType = '',
  fusionChatId = '',
  isDeleteChatHistory,
  isAuthority,
  isHomePage,
}: AppQAProps) => {
  const { setAppDetail, setInputGuides, configurations } = useOrchestrationStore();
  const [currentView, setCurrentView] = useState<string>('chat');
  const [chatMessage, setChatMessage] = useState<string>('');
  const [chatId, setChatId] = useState<string>('');
  const { isPc } = useWindowWidth();

  // const searchParams = new URLSearchParams(location.search);
  // const appId = searchParams.get('appId') || '';
  const { appId, chatId: initChatId } = useParams() as { appId: string; chatId: string };

  const isConfigAvailable = configurations.length != 0;

  const handleViewChange = (
    view: 'homepage' | 'history' | 'chat' | 'dashboard',
    message?: string,
  ) => {
    setContentType && setContentType(view);
    setCurrentView(view);
    if (message) {
      setChatMessage(message);
      setChatId(''); // 清空chatId，因为是从新消息开始聊天
    }
  };
  useEffect(() => {
    if (isHomePage != null) {
      setCurrentView('homepage');
    }
  }, [isHomePage]);

  useEffect(() => {
    if (initChatId) {
      setContentType && setContentType('chat');
      setChatId(initChatId);
    }
  }, []);

  const fetchInputGuides = async () => {
    if (!appId) return;
    try {
      const res = await orchestrationService.getAppInputGuide(appId);
      if (res.input_guide) {
        const guides = res.input_guide.map((guide: string, index: number) => ({
          id: String(index + 1),
          content: guide,
        }));
        setInputGuides(guides);
      }
    } catch (error) {
      message.error('获取输入引导失败');
    }
  };

  useEffect(() => {
    const fetchAppDetail = async () => {
      if (!appId) {
        // message.error('未获取到应用ID');
        return;
      }

      try {
        const isInChatPage = location.pathname.includes('/apps/chat');
        const appDetail = await orchestrationService.getAppDetailV2(
          appId,
          isInChatPage ? AppWorkbenchType.public : AppWorkbenchType.public,
        );
        // 设置应用详情到store
        console.log('bbbb');
        setAppDetail(appDetail);
      } catch (error) {
        message.error('获取应用详情失败');
      } finally {
      }
    };
    fetchAppDetail();
    fetchInputGuides();
    setCurrentView(contentType);
    return () => {};
  }, [contentType, fusionChatId]);

  const handleChatItemClick = (selectedChatId: string) => {
    setChatId(selectedChatId);
    setChatMessage(''); // 清空message，因为是加载已有对话
    setCurrentView('chat');
  };

  useEffect(() => {
    if (fusionChatId === '') {
      return;
    }
    if (contentType === 'collect-chat') {
      setCurrentView('homepage');
    } else if (contentType == 'history-chat') {
      setChatId(fusionChatId);
      setChatMessage(''); // 清空message，因为是加载已有对话
      setCurrentView('chat');
    }
  }, [fusionChatId]);

  return (
    <div className={`app-qa-container ${!isPc ? 'flex h-full w-full' : ''}`}>
      <Layout
        style={{
          height: '100%',
          overflow: 'hidden',
          background: 'transparent',
        }}
      >
        <Layout.Content className="app-qa-content" style={{ flex: 1, overflow: 'auto' }}>
          {currentView === 'homepage' && (
            <Homepage
              onChatStart={(msg) => handleViewChange('chat', msg)}
              workflowDebug={workflowDebug}
              widthFlag={false}
            />
          )}
          {currentView === 'history' && (
            <HistoryChat
              onChatItemClick={handleChatItemClick}
              isDeleteChatHistory={isDeleteChatHistory}
            />
          )}
          {currentView === 'chat' && (
            <Chat
              workflowDebug={workflowDebug}
              initialMessage={chatMessage}
              chatId={chatId}
              isAuthority={isAuthority}
              onStartChat={onStartChat}
              onUpdateHistory={onUpdateHistory}
            />
          )}
          {currentView === 'dashboard' && <Dashboard />}
        </Layout.Content>
      </Layout>
    </div>
  );
};

export default AppQA;
